<script setup>

import {Delete, Edit, Plus} from "@element-plus/icons-vue";
import {onMounted, reactive, ref} from "vue";
import {useUserInfoStore} from "@/stores/userInfo";
import {deleteVehicles, insertVehicles, updateVehicles, vehiclesList} from "@/api/vehicles";
import {ElMessage, ElMessageBox} from "element-plus";
import {insertOrders} from "@/api/orders";
//分页条数据模型
const pageNo = ref(1)//当前页
const total = ref(0)//总条数
const pageSize = ref(6)//每页条数
const vehiclesListData = ref([])
const dialogVisible = ref(false)
const titleName = ref('')
const userInfoStore = useUserInfoStore();

// 图片回显url
const imageUrl = ref('')


// 文件上传回调
const handleAvatarSuccess = (
    response,
    uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  formData.value.images = response.message
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/png') {
    ElMessage.error('只能上传图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 婚车添加、编辑表单数据模型
const formData = ref({
  platenNumber: '',
  brand: '',
  model: '',
  color:'',
  year: '',
  seats: '',
  vehicleType: '',
  purchaseDate: '',
  insuranceExpiry: '',
  status: '',
  dailyRate: '',
  description: '',
  images:''
})
const form = ref(null)
const formLabelWidth = '140px'
// 获取婚车列表数据
const getVehiclesList = ()=>{
  const params = {
    params:{
      pageNo: pageNo.value,
      pageSize: pageSize.value,
      platenNumber : formData.value.platenNumber,
      model: formData.value.model
    }
  }
  // 发送请求
  vehiclesList(params).then(res=>{
    vehiclesListData.value= res.data.records
    total.value= res.data.count
  })

}
//
onMounted(()=>{
  getVehiclesList()
})
// 重置
const resetParams = ()=>{
  formData.value.platenNumber = ''
  formData.value.brand = ''
  formData.value.model = ''
  formData.value.color = ''
  formData.value.year = ''
  formData.value.seats = ''
  formData.value.vehicleType = ''
  formData.value.purchaseDate = ''
  formData.value.insuranceExpiry = ''
  formData.value.status = ''
  formData.value.dailyRate = ''
  formData.value.description = ''
  formData.value.images = ''
  getVehiclesList()
}

// 当每页条数发生了变化，会调用
const handleSizeChange = (val) => {
  pageSize.value = val
  getVehiclesList()
}
// 当当前页面发生变化，会调用
const handleCurrentChange = (val) => {
  pageNo.value = val
  getVehiclesList()
}
// 删除婚车
const deleteById=(id)=>{
  ElMessageBox.confirm(
      '确认删除吗，删除后不可恢复?',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        deleteVehicles({id:id}).then(res=>{
          if (res.success) {
            ElMessage.success(res.message)
            getVehiclesList()
          }
        })
      })
      .catch(() => {
      })
}

// 婚车添加打开dialog
const showAddDialog =(title)=>{
  dialogVisible.value = true
  titleName.value = title
  form.value.resetFields()
}

// 婚车添加
const addVehicles = () => {
  form.value.validate((valid)=>{
    if (valid) {

      if (formData.value.purchaseDate)formData.value.purchaseDate= JSON.stringify(formData.value.purchaseDate).replace("T", " ").replace('"', '').split(".")[0];
      if (formData.value.insuranceExpiry)formData.value.insuranceExpiry= JSON.stringify(formData.value.insuranceExpiry).replace("T", " ").replace('"', '').split(".")[0];
      insertVehicles(formData.value).then(res=>{
        if (res.success) {
          ElMessage.success(res.message)
          dialogVisible.value= false
          resetParams()
        }
      })
    }
  })
}

// 清空表单

// 打开编辑dialog
const showEditDialog=(row,title)=>{
  formData.value= {...row}
  formData.value.orderNumber = row.id;
  formData.value.typeid = 2;
  formData.value.customerid = localStorage.getItem('userid');
  formData.value.paymentStatus = "未支付";
  imageUrl.value = `/api/file/download.do?filename=${row.images}`
  titleName.value = title
  dialogVisible.value = true
}
// 更新婚车
const editVehicles=()=>{
  if (formData.value.purchaseDate)formData.value.purchaseDate= JSON.stringify(formData.value.purchaseDate).replace("T", " ").replace('"', '').split(".")[0];
  if (formData.value.insuranceExpiry)formData.value.insuranceExpiry= JSON.stringify(formData.value.insuranceExpiry).replace("T", " ").replace('"', '').split(".")[0];

  updateVehicles(formData.value).then(res=>{
    if (res.success) {
      ElMessage.success(res.message)
      dialogVisible.value= false
      resetParams()
    }
  })
}
const dialogVisibleClose=()=>{
  dialogVisible.value= false
  resetParams()
}
// 表单校验
const rules = {
  vehiclesname: [
    {required: true, message: '请输入婚车名', trigger: 'blur'},
    {min: 3, max: 16, message: '长度为3-16位', trigger: 'blur'},
  ]
}

const addOrders = () => {
  form.value.validate((valid)=>{
    if (valid) {

      if (formData.value.createdAt)formData.value.createdAt= JSON.stringify(formData.value.createdAt).replace("T", " ").replace('"', '').split(".")[0];
      insertOrders(formData.value).then(res=>{
        if (res.success) {
          ElMessage.success(res.message)
          dialogVisible.value= false
          resetParams()
        }
      })
    }
  })
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>婚车管理</span>
        <div class="extra">
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="车牌号：">
        <el-input v-model="formData.platenNumber" placeholder="请输入车牌号"></el-input>
      </el-form-item>
      <el-form-item label="名称：">
        <el-input v-model="formData.model" placeholder="请输入名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getVehiclesList">搜索</el-button>
        <el-button @click="resetParams">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 婚车列表 -->

    <el-row>
      <el-col
          v-for="(o, index) in vehiclesListData"
          :key="o"
          :span="6"
          :offset="index >= 0 ? 2 : 0"
      >
        <el-card :body-style="{ padding: '0px' }">
          <img
              :src="`/api/file/download.do?filename=${o.images}`"
              class="image"
          />
          <div style="padding: 14px">
            <span>{{ o.model }}</span><br>
            <span>品牌：{{ o.brand }}</span><br>
            <span>年份：{{ o.year }}</span><br>
            <span>颜色：{{ o.color }}</span><br>
            <div class="bottom">
              <el-button text class="button" type="primary" @click="showEditDialog(o,'婚车下单')">下单</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <hr>

    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[6 ,12, 18]"
                   layout="jumper, total, sizes, prev, pager, next" background :total="total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" style="margin-top: 20px; justify-content: flex-end"/>
  </el-card>

<!--  添加婚车对话框-->
  <!--  添加订单对话框-->
  <el-dialog
      v-model="dialogVisible"
      :title="titleName"
      width="500"
  >
    <el-form ref="form" :rules="rules" :model="formData" label-width="auto" style="max-width: 600px">
      <el-form-item  label="订单编号" prop="orderNumber">
        <el-input type="text" v-model="formData.orderNumber" disabled  />
      </el-form-item>
      <!--      <el-form-item label="订单类型" prop="typeid">
              <el-input type="text" v-model="formData.typeid"  />
            </el-form-item>-->
      <el-form-item label="顾客编号" prop="customerid">
        <el-input type="text" v-model="formData.customerid" disabled />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-input type="text" v-model="formData.startTime"  />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-input type="text" v-model="formData.endTime"  />
      </el-form-item>
            <el-form-item label="行程描述" prop="routeDescription">
              <el-input type="text" v-model="formData.routeDescription"  />
            </el-form-item>
            <el-form-item label="预计总里程" prop="totalDistance">
              <el-input type="text" v-model="formData.totalDistance"  />
            </el-form-item>
      <!--      <el-form-item label="状态" prop="status">
              <el-input type="text" v-model="formData.status"  />
            </el-form-item>-->
      <el-form-item label="订单总金额" prop="totalAmount">
        <el-input type="text" v-model="formData.totalAmount"  />
      </el-form-item>
      <el-form-item label="支付状态" prop="paymentStatus">
        <el-input type="text" v-model="formData.paymentStatus" disabled />
      </el-form-item>
      <!--      <el-form-item label="创建时间" prop="createdAt">
              <el-input type="text" v-model="formData.createdAt"  />
            </el-form-item>-->

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisibleClose">取消</el-button>
        <el-button type="primary" @click="addOrders()">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>


</template>

<style scoped lang="scss">
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.time {
  font-size: 12px;
  color: #999;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button {
  padding: 0;
  min-height: auto;
}

.image {
  width: 100%;
  display: block;
}

.el-col {
  margin-bottom: 5px;
}
</style>